package com.imooc.order.service.impl;

import com.imooc.order.dataobject.OrderDetail;
import com.imooc.order.dataobject.OrderMaster;
import com.imooc.order.dto.OrderDTO;
import com.imooc.order.enums.OrderStatusEnum;
import com.imooc.order.enums.PayStatusEnum;
import com.imooc.order.enums.ResultEnum;
import com.imooc.order.exception.OrderException;
import com.imooc.order.repository.OrderDetailRepository;
import com.imooc.order.repository.OrderMasterRepository;
import com.imooc.order.service.OrderService;
import com.imooc.order.util.KeyUtil;
import com.imooc.product.client.ProductClient;
import com.imooc.product.common.DecreaseStockInput;
import com.imooc.product.common.ProductInfoOutput;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author steve
 * @date 2020/6/16 11:33
 */
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMasterRepository orderMasterRepository;
    @Autowired
    private OrderDetailRepository orderDetailRepository;
    @Autowired
    private ProductClient productClient;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderDTO create(OrderDTO orderDTO) {
        String orderId = KeyUtil.genUniqueKey();

        //查询商品信息（调用商品服务）
        //构造商品id列表
        List<String> productIdList = orderDTO.getOrderDetailList().stream().map(OrderDetail::getProductId).collect(Collectors.toList());
        List<ProductInfoOutput> productInfoList = productClient.listForOrder(productIdList);
        //计算总价
        BigDecimal totalAmount = new BigDecimal(0);
        for (OrderDetail orderDetail : orderDTO.getOrderDetailList()) {
            for (ProductInfoOutput productInfo : productInfoList) {
                if (productInfo.getProductId().equals(orderDetail.getProductId())) {
                    //单价*数量+当前总价
                    BigDecimal price = productInfo.getProductPrice();
                    BigDecimal amount = new BigDecimal(orderDetail.getProductQuantity());
                    totalAmount = price.multiply(amount).add(totalAmount);
                }
                BeanUtils.copyProperties(productInfo, orderDetail);
                //设置订单详情id
                orderDetail.setDetailId(KeyUtil.genUniqueKey());
                //订单id只有一个，因此需要在外面定义好orderId
                orderDetail.setOrderId(orderId);
                //订单详情入库
                orderDetailRepository.save(orderDetail);
            }
        }

        //扣库存
        //构造购物车列表
        List<DecreaseStockInput> cartDTOList = orderDTO.getOrderDetailList().stream().map(e -> new DecreaseStockInput(e.getProductId(), e.getProductQuantity())).collect(Collectors.toList());
        productClient.decreaseStock(cartDTOList);

        OrderMaster orderMaster = new OrderMaster();
        //构建订单id
        orderDTO.setOrderId(KeyUtil.genUniqueKey());
        //这里需要把orderDTO的orderId保存到orderMaster中，因此需要先复制
        BeanUtils.copyProperties(orderDTO, orderMaster);
        //构建数据
        orderMaster.setOrderAmount(totalAmount);
        orderMaster.setOrderStatus(OrderStatusEnum.NEW.getCode());
        orderMaster.setPayStatus(PayStatusEnum.WAIT.getCode());
        //订单入库
        orderMasterRepository.save(orderMaster);
        //根据API文档，需要返回orderId
        return orderDTO;
    }

    @Override
    public OrderDTO findOrderById(String orderId) {
        return null;
    }

    @Override
    public Page<OrderDTO> findAll(String buyerOpenid, Pageable pageable) {
        return null;
    }

    @Override
    public OrderDTO cancel(OrderDTO orderDTO) {
        return null;
    }

    @Override
    public OrderDTO finished(String orderId) {
        //1.数据库查找订单
        OrderMaster orderMaster = orderMasterRepository.findByOrderId(orderId);
        if (orderMaster == null) {
            //订单数据查找为空
            throw new OrderException(ResultEnum.ORDER_NOT_EXIST);
        }
        //2.判断订单状态
        if (!OrderStatusEnum.NEW.getCode().equals(orderMaster.getOrderStatus())) {
            //如果不是新订单状态
            throw new OrderException(ResultEnum.ORDER_STATUS_ERROR);
        }
        //3.修改订单状态为完成状态
        orderMaster.setOrderStatus(OrderStatusEnum.FINISHED.getCode());
        //4.重新保存到数据库
        orderMasterRepository.save(orderMaster);

        //查询订单详情
        List<OrderDetail> orderDetailList = orderDetailRepository.findByOrderId(orderId);
        if (CollectionUtils.isEmpty(orderDetailList)) {
            //如果订单详情为空
            throw new OrderException(ResultEnum.ORDER_DETAIL_NOT_EXIST);
        }
        //拷贝数据
        OrderDTO orderDTO = new OrderDTO();
        BeanUtils.copyProperties(orderMaster, orderDTO);
        //把订单详情数据设置到orderDTO
        orderDTO.setOrderDetailList(orderDetailList);

        return orderDTO;
    }
}
